package client.comm.baoding.ui

import android.content.Intent
import android.view.LayoutInflater
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import client.comm.commlib.toast.toast
import client.comm.commlib.utils.StoreUtil
import client.comm.baoding.R
import client.comm.baoding.api.bean.SearchVal
import client.comm.baoding.databinding.ActivitySearchBinding
import client.comm.baoding.databinding.LayoutSearchitemBinding
import client.comm.baoding.dialog.MsgTitleDialog
import client.comm.baoding.ui.vm.SearchModel
import client.comm.baoding.BaseMiddleActivity
class SearchActivity : BaseMiddleActivity<SearchModel, ActivitySearchBinding>() {
    override fun getLayout(): Int {
        return R.layout.activity_search
    }

    override fun initViewModel(): SearchModel = createViewModel()

    override fun initView() {
        binding.event = this
        binding.vm = viewModel
        viewModel.ret.observe(this, Observer {
            it?.let {
                binding.searchHisWrap.removeAllViews()
                for (e in it.bb) {
                    DataBindingUtil.inflate<LayoutSearchitemBinding>(
                        LayoutInflater.from(this), R.layout.layout_searchitem,
                        binding.searchHisWrap, false
                    ).apply {
                        tv.text = e
                        root.setOnClickListener {
                            startActivity(
                                Intent(
                                    this@SearchActivity,
                                    SearchRetActivity::class.java
                                ).apply {
                                    putExtra("word", e)
                                })
                            finish()
                        }
                        binding.searchHisWrap.addView(root)
                    }
                }
            }
        })
        viewModel.getData()
    }

    fun goSearch() {
        val str = viewModel.wordVal.value
        if (str.isNullOrEmpty()) {
            toast("请输入内容")
            return
        }
        val ss = arrayListOf<String>()
        viewModel.ret.value?.bb?.let {
            ss.addAll(it)
        }
        ss.add(str)
        StoreUtil.saveBean(this, SearchVal(ss))

        startActivity(Intent(this, SearchRetActivity::class.java).apply {
            putExtra("word", str)
        })
        finish()
    }

    fun del() {
        MsgTitleDialog(this).apply {
            title = "确认清空记录?"
            okTxt = "清空"
            ok = {
                val bb = SearchVal(ArrayList<String>())
                viewModel.ret.value = bb
                StoreUtil.saveBean(this@SearchActivity, bb)
            }
        }.show()

    }
}